<template>
  <div class="process-config">
    <!-- 页面标题 -->
    <div class="page-header">
      <h2>异常订单处理流程配置</h2>
      <div class="header-actions">
        <el-button type="primary" @click="handleAddProcess">
          <el-icon><Plus /></el-icon>新建流程
        </el-button>
      </div>
    </div>

    <!-- 流程列表 -->
    <el-card class="process-list">
      <el-table
        v-loading="loading"
        :data="processList"
        border
        style="width: 100%"
      >
        <el-table-column type="index" width="50" />
        <el-table-column prop="name" label="流程名称" min-width="150" />
        <el-table-column prop="type" label="异常类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getExceptionTypeTag(row.type)">
              {{ getExceptionTypeLabel(row.type) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="nodeCount" label="节点数量" width="100" />
        <el-table-column prop="handlerCount" label="处理角色" width="100" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-switch
              v-model="row.status"
              :active-value="1"
              :inactive-value="0"
              @change="handleStatusChange(row)"
            />
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" min-width="180" />
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" link @click="handleEdit(row)">编辑</el-button>
            <el-button type="success" link @click="handleCopy(row)">复制</el-button>
            <el-button type="warning" link @click="handlePreview(row)">预览</el-button>
            <el-button type="danger" link @click="handleDelete(row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 流程编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogType === 'add' ? '新建流程' : '编辑流程'"
      width="800px"
    >
      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="流程名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入流程名称" />
        </el-form-item>
        <el-form-item label="异常类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择异常类型">
            <el-option label="退款纠纷" value="refund" />
            <el-option label="服务投诉" value="complaint" />
            <el-option label="商品问题" value="product" />
            <el-option label="其他异常" value="other" />
          </el-select>
        </el-form-item>
        <el-form-item label="流程节点" prop="nodes">
          <div class="node-list">
            <draggable
              v-model="form.nodes"
              item-key="id"
              handle=".drag-handle"
              @end="handleNodeDragEnd"
            >
              <template #item="{ element, index }">
                <div class="node-item">
                  <div class="node-header">
                    <el-icon class="drag-handle"><Rank /></el-icon>
                    <span class="node-title">节点 {{ index + 1 }}</span>
                    <el-button
                      type="danger"
                      link
                      @click="handleRemoveNode(index)"
                    >
                      删除
                    </el-button>
                  </div>
                  <div class="node-content">
                    <el-form-item
                      :prop="'nodes.' + index + '.name'"
                      :rules="{ required: true, message: '请输入节点名称', trigger: 'blur' }"
                    >
                      <el-input v-model="element.name" placeholder="节点名称" />
                    </el-form-item>
                    <el-form-item
                      :prop="'nodes.' + index + '.type'"
                      :rules="{ required: true, message: '请选择节点类型', trigger: 'change' }"
                    >
                      <el-select v-model="element.type" placeholder="节点类型">
                        <el-option label="处理节点" value="process" />
                        <el-option label="审核节点" value="approve" />
                        <el-option label="通知节点" value="notice" />
                        <el-option label="结束节点" value="end" />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="element.type === 'process'"
                      :prop="'nodes.' + index + '.handlers'"
                      :rules="{ required: true, message: '请选择处理角色', trigger: 'change' }"
                    >
                      <el-select
                        v-model="element.handlers"
                        multiple
                        collapse-tags
                        placeholder="处理角色"
                      >
                        <el-option
                          v-for="role in roleList"
                          :key="role.id"
                          :label="role.name"
                          :value="role.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="element.type === 'approve'"
                      :prop="'nodes.' + index + '.approvers'"
                      :rules="{ required: true, message: '请选择审核角色', trigger: 'change' }"
                    >
                      <el-select
                        v-model="element.approvers"
                        multiple
                        collapse-tags
                        placeholder="审核角色"
                      >
                        <el-option
                          v-for="role in roleList"
                          :key="role.id"
                          :label="role.name"
                          :value="role.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="element.type === 'notice'"
                      :prop="'nodes.' + index + '.noticeType'"
                      :rules="{ required: true, message: '请选择通知类型', trigger: 'change' }"
                    >
                      <el-select v-model="element.noticeType" placeholder="通知类型">
                        <el-option label="短信通知" value="sms" />
                        <el-option label="邮件通知" value="email" />
                        <el-option label="系统通知" value="system" />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="element.type === 'notice'"
                      :prop="'nodes.' + index + '.noticeTemplate'"
                      :rules="{ required: true, message: '请选择通知模板', trigger: 'change' }"
                    >
                      <el-select v-model="element.noticeTemplate" placeholder="通知模板">
                        <el-option
                          v-for="template in noticeTemplateList"
                          :key="template.id"
                          :label="template.name"
                          :value="template.id"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="element.type !== 'end'"
                      :prop="'nodes.' + index + '.nextNodes'"
                      :rules="{ required: true, message: '请选择下一节点', trigger: 'change' }"
                    >
                      <el-select
                        v-model="element.nextNodes"
                        multiple
                        collapse-tags
                        placeholder="下一节点"
                      >
                        <el-option
                          v-for="(node, idx) in form.nodes"
                          :key="idx"
                          :label="'节点 ' + (idx + 1)"
                          :value="idx"
                          :disabled="idx <= index"
                        />
                      </el-select>
                    </el-form-item>
                    <el-form-item
                      v-if="element.type === 'process' || element.type === 'approve'"
                      :prop="'nodes.' + index + '.timeLimit'"
                    >
                      <el-input-number
                        v-model="element.timeLimit"
                        :min="0"
                        :max="72"
                        placeholder="处理时限(小时)"
                      />
                    </el-form-item>
                  </div>
                </div>
              </template>
            </draggable>
            <div class="node-actions">
              <el-button type="primary" @click="handleAddNode">
                <el-icon><Plus /></el-icon>添加节点
              </el-button>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="form.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 流程预览对话框 -->
    <el-dialog
      v-model="previewVisible"
      title="流程预览"
      width="800px"
    >
      <div class="process-preview">
        <div class="node-flow">
          <div
            v-for="(node, index) in currentProcess.nodes"
            :key="index"
            class="flow-node"
            :class="node.type"
          >
            <div class="node-header">
              <span class="node-title">{{ node.name }}</span>
              <el-tag size="small" :type="getNodeTypeTag(node.type)">
                {{ getNodeTypeLabel(node.type) }}
              </el-tag>
            </div>
            <div class="node-content">
              <template v-if="node.type === 'process'">
                <div class="node-info">
                  <span class="label">处理角色：</span>
                  <el-tag
                    v-for="handler in node.handlers"
                    :key="handler"
                    size="small"
                    class="mx-1"
                  >
                    {{ getRoleName(handler) }}
                  </el-tag>
                </div>
                <div class="node-info" v-if="node.timeLimit">
                  <span class="label">处理时限：</span>
                  <span>{{ node.timeLimit }}小时</span>
                </div>
              </template>
              <template v-if="node.type === 'approve'">
                <div class="node-info">
                  <span class="label">审核角色：</span>
                  <el-tag
                    v-for="approver in node.approvers"
                    :key="approver"
                    size="small"
                    class="mx-1"
                  >
                    {{ getRoleName(approver) }}
                  </el-tag>
                </div>
                <div class="node-info" v-if="node.timeLimit">
                  <span class="label">审核时限：</span>
                  <span>{{ node.timeLimit }}小时</span>
                </div>
              </template>
              <template v-if="node.type === 'notice'">
                <div class="node-info">
                  <span class="label">通知类型：</span>
                  <el-tag size="small">
                    {{ getNoticeTypeLabel(node.noticeType) }}
                  </el-tag>
                </div>
                <div class="node-info">
                  <span class="label">通知模板：</span>
                  <span>{{ getNoticeTemplateName(node.noticeTemplate) }}</span>
                </div>
              </template>
            </div>
            <div class="node-arrows" v-if="node.nextNodes?.length">
              <div
                v-for="nextIndex in node.nextNodes"
                :key="nextIndex"
                class="arrow"
              >
                <el-icon><ArrowRight /></el-icon>
                <span>节点 {{ nextIndex + 1 }}</span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Rank, ArrowRight } from '@element-plus/icons-vue'
import draggable from 'vuedraggable'
import {
  getMerchantOrderExceptionProcessList,
  addMerchantOrderExceptionProcess,
  updateMerchantOrderExceptionProcess,
  deleteMerchantOrderExceptionProcess,
  copyMerchantOrderExceptionProcess,
  updateMerchantOrderExceptionProcessStatus,
  getMerchantRoleList,
  getMerchantNoticeTemplateList
} from '@/api/merchant'

// 流程列表数据
const loading = ref(false)
const processList = ref([])
const roleList = ref([])
const noticeTemplateList = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add')
const formRef = ref(null)
const form = reactive({
  id: '',
  name: '',
  type: '',
  nodes: [],
  remark: ''
})

// 预览相关
const previewVisible = ref(false)
const currentProcess = ref({})

// 表单验证规则
const rules = {
  name: [
    { required: true, message: '请输入流程名称', trigger: 'blur' },
    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'blur' }
  ],
  type: [
    { required: true, message: '请选择异常类型', trigger: 'change' }
  ],
  nodes: [
    { required: true, message: '请添加流程节点', trigger: 'change' },
    { type: 'array', min: 1, message: '至少添加一个节点', trigger: 'change' }
  ]
}

// 获取流程列表
const getProcessList = async () => {
  loading.value = true
  try {
    const { data } = await getMerchantOrderExceptionProcessList()
    processList.value = data
  } catch (error) {
    console.error('获取流程列表失败:', error)
    ElMessage.error('获取流程列表失败')
  } finally {
    loading.value = false
  }
}

// 获取角色列表
const getRoleList = async () => {
  try {
    const { data } = await getMerchantRoleList()
    roleList.value = data
  } catch (error) {
    console.error('获取角色列表失败:', error)
  }
}

// 获取通知模板列表
const getNoticeTemplateList = async () => {
  try {
    const { data } = await getMerchantNoticeTemplateList()
    noticeTemplateList.value = data
  } catch (error) {
    console.error('获取通知模板列表失败:', error)
  }
}

// 新建流程
const handleAddProcess = () => {
  dialogType.value = 'add'
  Object.keys(form).forEach(key => {
    form[key] = Array.isArray(form[key]) ? [] : ''
  })
  dialogVisible.value = true
}

// 编辑流程
const handleEdit = (row) => {
  dialogType.value = 'edit'
  Object.keys(form).forEach(key => {
    form[key] = row[key]
  })
  dialogVisible.value = true
}

// 复制流程
const handleCopy = async (row) => {
  try {
    await copyMerchantOrderExceptionProcess(row.id)
    ElMessage.success('复制成功')
    getProcessList()
  } catch (error) {
    console.error('复制流程失败:', error)
  }
}

// 预览流程
const handlePreview = (row) => {
  currentProcess.value = row
  previewVisible.value = true
}

// 删除流程
const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm('确认删除该流程吗？', '提示', {
      type: 'warning'
    })
    await deleteMerchantOrderExceptionProcess(row.id)
    ElMessage.success('删除成功')
    getProcessList()
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除流程失败:', error)
    }
  }
}

// 更新状态
const handleStatusChange = async (row) => {
  try {
    await updateMerchantOrderExceptionProcessStatus({
      id: row.id,
      status: row.status
    })
    ElMessage.success('更新成功')
  } catch (error) {
    console.error('更新状态失败:', error)
    row.status = row.status === 1 ? 0 : 1
  }
}

// 添加节点
const handleAddNode = () => {
  form.nodes.push({
    id: Date.now(),
    name: '',
    type: 'process',
    handlers: [],
    approvers: [],
    noticeType: '',
    noticeTemplate: '',
    nextNodes: [],
    timeLimit: 0
  })
}

// 删除节点
const handleRemoveNode = (index) => {
  form.nodes.splice(index, 1)
}

// 节点拖拽结束
const handleNodeDragEnd = () => {
  // 更新节点顺序
  form.nodes.forEach((node, index) => {
    node.nextNodes = node.nextNodes.filter(nextIndex => nextIndex < form.nodes.length)
  })
}

// 提交表单
const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    if (dialogType.value === 'add') {
      await addMerchantOrderExceptionProcess(form)
      ElMessage.success('添加成功')
    } else {
      await updateMerchantOrderExceptionProcess(form)
      ElMessage.success('更新成功')
    }
    dialogVisible.value = false
    getProcessList()
  } catch (error) {
    console.error('保存流程失败:', error)
  }
}

// 获取异常类型标签类型
const getExceptionTypeTag = (type) => {
  const typeMap = {
    refund: 'danger',
    complaint: 'warning',
    product: 'error',
    other: 'info'
  }
  return typeMap[type] || ''
}

// 获取异常类型标签文本
const getExceptionTypeLabel = (type) => {
  const typeMap = {
    refund: '退款纠纷',
    complaint: '服务投诉',
    product: '商品问题',
    other: '其他异常'
  }
  return typeMap[type] || type
}

// 获取节点类型标签类型
const getNodeTypeTag = (type) => {
  const typeMap = {
    process: 'primary',
    approve: 'warning',
    notice: 'success',
    end: 'info'
  }
  return typeMap[type] || ''
}

// 获取节点类型标签文本
const getNodeTypeLabel = (type) => {
  const typeMap = {
    process: '处理节点',
    approve: '审核节点',
    notice: '通知节点',
    end: '结束节点'
  }
  return typeMap[type] || type
}

// 获取通知类型标签文本
const getNoticeTypeLabel = (type) => {
  const typeMap = {
    sms: '短信通知',
    email: '邮件通知',
    system: '系统通知'
  }
  return typeMap[type] || type
}

// 获取角色名称
const getRoleName = (roleId) => {
  const role = roleList.value.find(r => r.id === roleId)
  return role ? role.name : roleId
}

// 获取通知模板名称
const getNoticeTemplateName = (templateId) => {
  const template = noticeTemplateList.value.find(t => t.id === templateId)
  return template ? template.name : templateId
}

onMounted(() => {
  getProcessList()
  getRoleList()
  getNoticeTemplateList()
})
</script>

<style lang="scss" scoped>
.process-config {
  padding: 20px;

  .page-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20px;

    h2 {
      margin: 0;
      font-size: 20px;
      font-weight: 500;
    }
  }

  .process-list {
    margin-bottom: 20px;
  }

  .node-list {
    .node-item {
      margin-bottom: 20px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;

      .node-header {
        display: flex;
        align-items: center;
        margin-bottom: 15px;

        .drag-handle {
          cursor: move;
          margin-right: 10px;
          color: #909399;
        }

        .node-title {
          flex: 1;
          font-weight: 500;
        }
      }

      .node-content {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        gap: 15px;
      }
    }

    .node-actions {
      margin-top: 20px;
      text-align: center;
    }
  }

  .process-preview {
    .node-flow {
      display: flex;
      flex-direction: column;
      gap: 20px;

      .flow-node {
        padding: 15px;
        border: 1px solid #dcdfe6;
        border-radius: 4px;

        &.process {
          border-left: 4px solid #409eff;
        }

        &.approve {
          border-left: 4px solid #e6a23c;
        }

        &.notice {
          border-left: 4px solid #67c23a;
        }

        &.end {
          border-left: 4px solid #909399;
        }

        .node-header {
          display: flex;
          justify-content: space-between;
          align-items: center;
          margin-bottom: 10px;

          .node-title {
            font-weight: 500;
          }
        }

        .node-content {
          .node-info {
            margin-bottom: 8px;
            font-size: 14px;

            .label {
              color: #606266;
              margin-right: 8px;
            }

            .mx-1 {
              margin: 0 4px;
            }
          }
        }

        .node-arrows {
          margin-top: 10px;
          padding-top: 10px;
          border-top: 1px dashed #dcdfe6;

          .arrow {
            display: flex;
            align-items: center;
            gap: 5px;
            color: #606266;
            font-size: 14px;
          }
        }
      }
    }
  }
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style> 